#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <iomanip>

std::string directory = "src/build/";  // 目标目录

// 截断幂函数的差商
double t_ftn(int degree, const std::vector<double>& t_divided, double x) {
    int n = t_divided.size();
    std::vector<double> d_diff(n);
    
    for (int i = 0; i < n; ++i) {
        if (t_divided[i] - x >= 0) {
            d_diff[i] = pow(t_divided[i] - x, degree);
        } else {
            d_diff[i] = 0;
        }
    }

    for (int level = 1; level < n; ++level) {
        for (int i = n - 1; i >= level; --i) {
            d_diff[i] = (d_diff[i] - d_diff[i - 1]) / (t_divided[i] - t_divided[i - level]);
        }
    }
    
    return d_diff.back();
}

void saveToFile(const std::string& file_name, const std::vector<double>& x, const std::vector<double>& y) {
    std::ofstream file(directory + file_name + ".csv");
        if (!file.is_open()) {
            std::cerr << "Failed to open file" << std::endl;
        }
        for (size_t i = 0; i < x.size(); ++i) {
            file << x[i] << "," << y[i] << std::endl;
        }
    file.close();
}

int main() {
    std::vector<double> data1={0,1,2};
    std::vector<double> x_p1;
    for(double x=-1.0; x<=3.0; x+=0.01){
        x_p1.push_back(x);
    }
    for(int i=0; i<data1.size(); i++){
        for(int j=i; j<data1.size(); j++){
            std::vector<double> y_p;
            std::vector<double> knots(data1.begin() + j - i, data1.begin() + j + 1);
            for (double t : x_p1) {
                y_p.push_back(t_ftn(1, knots, t));
            }
            saveToFile("data_F_1_" + std::to_string(i) + "_" + std::to_string(j), x_p1, y_p);
        }
    }

    std::vector<double> data2={0,1,2,3};
    std::vector<double> x_p2;
    for(double x=-1.0; x<=4.0; x+=0.01){
        x_p2.push_back(x);
    }
    for(int i=0; i<data2.size(); i++){
        for(int j=i; j<data2.size(); j++){
            std::vector<double> y_p;
            std::vector<double> knots(data2.begin() + j - i, data2.begin() + j + 1);
            for (double t : x_p2) {
                y_p.push_back(t_ftn(2, knots, t));
            }
            saveToFile("data_F_2_" + std::to_string(i) + "_" + std::to_string(j), x_p2, y_p);
        }
    }
}
